﻿using System.IO;



using System.Data;
using System.Collections;
using System.Reflection;
using System;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.OpenXmlFormats.Spreadsheet;
using Microsoft.AspNetCore.Http;

namespace ServiceWeb.Excel
{
    public class DaoChuExcel
    {
        //https://blog.csdn.net/wwwen/article/details/124453898
        //        //设置打印与网格线
        //        _sheet.PrintSetup.PaperSize = (short) PaperSize.A4_Small;  //a4纸打印
        //        _sheet.PrintSetup.Landscape = true;                       //横向打印
        //        _sheet.PrintSetup.FitWidth = 1;                           //所有列在一页  
        //        _sheet.PrintSetup.FitHeight = 0;                          //所有行在一页
        //        _sheet.FitToPage = true;                                  //这三条语句一起才起作用:  所有列在一页
        //        //_sheet.VerticallyCenter = true;                         //垂直居中
        //        _sheet.HorizontallyCenter = true;                         //水平居中
        //        _sheet.DisplayGridlines = false;                          //隐藏网格线

        //        //设置页眉页脚
        //        IFooter _footer = _sheet.Footer;
        //        _footer.Center ="第 "+ HSSFFooter.Page + " 页，共 " + HSSFFooter.NumPages+" 页";  
        //        _footer.Left = HSSFFooter.Font("宋体", "Italic")+ HSSFFooter.FontSize((short)6) + "部门电话";

        //        //设置页眉页脚的边距  0.5=2.5,一个点0.2,这里有点傻，勉强换算为自己想要的数据
        //        _sheet.PrintSetup.HeaderMargin = ((1.3 / 0.5) * 0.2f);
        //        _sheet.PrintSetup.FooterMargin = ((0.5 / 0.5) * 0.2f);

        //        //设置页边距
        //        _sheet.SetMargin(MarginType.LeftMargin, (1.1 / 0.5) * 0.2f);
        //        _sheet.SetMargin(MarginType.BottomMargin, (2.0/0.5)*0.2f);
        //        _sheet.SetMargin(MarginType.RightMargin, (0.9 / 0.5) * 0.2f);
        //        _sheet.SetMargin(MarginType.TopMargin, (4.3 / 0.5) * 0.2f);

        //        //打印标题行
        //        _wb.SetRepeatingRowsAndColumns(_sheetindex, 0,0, 0, titleRow);  //固定标题行，不需固定列
        //————————————————
        //版权声明：本文为CSDN博主「wwwen」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
        //原文链接：https://blog.csdn.net/wwwen/article/details/124453898


        public bool WriteExcel_FailExcel(DataTable dt, string downPath, string filename, ArrayList HeaderList, string title)
        {
            DataTable dttable = new DataTable();

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                dttable.Columns.Add();
            }
            for (int i = 0; i < HeaderList.Count; i++)
            {
                dttable.Columns[i].ColumnName = HeaderList[i].ToString();
            }


            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dttable.NewRow();
                for (int ii = 0; ii < dt.Columns.Count; ii++)
                {
                    dr[ii] = dt.Rows[i][ii].ToString();
                }
                dttable.Rows.Add(dr);
            }
            string path = "wwwroot/file/down/";
            string dir = path;
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            return NpoiExcelHelper.ExportDataToExcel(dttable, downPath, filename, title, "");
            //  return  ExcelHelp.ExcelFailExport(dttable, dir + "\\" + filename, title, "");


        }

        // public bool WriteExcel(DataTable dt, DataTable dtdlv)
        public bool WriteExcel(DataTable dt, string downPath, string filename, ArrayList HeaderList, string title)
        {

            //BaseClass.//Log4netFactory.WriteInfo("--", Startup.repository.Name, "导出 " + title + ",条数：" + dt.Rows.Count);
            DataTable dttable = new DataTable();

            for (int i = 0; i < dt.Columns.Count + 1; i++)
            {
                dttable.Columns.Add();
            }
            dttable.Columns[0].ColumnName = "序号";
            for (int i = 0; i < HeaderList.Count; i++)
            {
                dttable.Columns[i + 1].ColumnName = HeaderList[i].ToString();
            }

            DataRow dr;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dr = dttable.NewRow();
                dr[0] = i + 1;
                for (int ii = 0; ii < dt.Columns.Count; ii++)
                {
                    dr[ii + 1] = dt.Rows[i][ii].ToString();
                }
                dttable.Rows.Add(dr);
            }
            //return Tool.Files.NpoiExcelHelper.ExportDataToExcel(dttable, ((IWebHostEnvironment)Configini.Configini._iHostingEnvironment).ContentRootPath + "\\wwwroot\\file\\down\\" + filename + ".xlsx", title, "");
            //return Tools.Files.ExcelHelp.ExcelExport(dttable, ((IWebHostEnvironment)Configini.Configini._iHostingEnvironment).ContentRootPath + "\wwwroot\file\\down\\" + filename + ".xlsx", title, "");
            return NpoiExcelHelper.ExportDataToExcel(dttable, downPath, filename + ".xlsx", title, "");



        }

        public bool WriteExcel_New(DataTable dttable, string downPath, string filename, string title)
        {

            return NpoiExcelHelper.ExportDataToExcel(dttable, downPath, filename, title, "");

        }
        public bool WriteExcel_New(ArrayList HeadList, DataTable dttable, string downPath, string filename, string title)
        {


            return NpoiExcelHelper.ExportDataToExcel(HeadList, dttable, downPath, filename, title, "");

        }
        public bool WriteExcel_FailExcel(ArrayList HeadList, DataTable dttable, string downPath, string filename, string title)
        {


            return NpoiExcelHelper.WriteExcel_FailExcel(HeadList, dttable, downPath, filename, title, "");

        }
        public bool WriteExcel_New_Project(DataTable dttable, string downPath, string filename, string title, DataTable dtxls2)
        {

            return NpoiExcelHelper.ExcelProjectExport(dttable, downPath, filename, title, dtxls2);
        }


        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumn)
        {
            IWorkbook workbook = null;
            FileStream fs = null;
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook(fs);
                else if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(fs);

                if (sheetName != null)
                {
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {


                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (isFirstRowColumn)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null　　　　　　　

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            var cell = row.GetCell(j);
                            if (cell != null) //同理，没有数据的单元格都默认是null
                            {
                                string val = string.Empty;
                                if (row.GetCell(j).CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
                                {
                                    val = cell.DateCellValue.ToString();
                                }
                                else
                                {
                                    val = cell.ToString();
                                }
                                dataRow[j] = val;

                            }
                        }
                        data.Rows.Add(dataRow);
                    }
                }
                fs.Close();
                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }
    }
}